package application;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import IDao.*;
import org.apache.commons.io.FileUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DaoFactory {
	private static ApplicationContext ctx;
	public static FoodMapper foodMapper;
	public static FrequencyMapper frequencyMapper;
	public static PatientMapper patientMapper;
	public static PatientInfoMapper patientInfoMapper;
	public static BaseMapper baseMapper;

	public DaoFactory() {
		String path = System.getProperty("user.home");
		File file = new File(path, "fdsys");
		createDirectoryWhenNoExist(file);
		File dataFile = new File(path, "fdsys/data.db");
		if (!dataFile.exists() && !file.isFile()) {
			InputStream is = getClass().getResourceAsStream("data.db");
			try {
				FileUtils.copyInputStreamToFile(is, dataFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		File configFile = new File(path, "fdsys/config.xlsx");
		if (!configFile.exists() && !configFile.isFile()) {
			InputStream is = getClass().getResourceAsStream("config.xlsx");
			try {
				FileUtils.copyInputStreamToFile(is, configFile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		ctx = new ClassPathXmlApplicationContext("ApplicationContext.xml");
		foodMapper = (FoodMapper) ctx.getBean("foodMapper");
		frequencyMapper = (FrequencyMapper) ctx.getBean("frequencyMapper");
		patientMapper = (PatientMapper) ctx.getBean("patientMapper");
		patientInfoMapper = (PatientInfoMapper) ctx.getBean("patientInfoMapper");
		baseMapper = (BaseMapper) ctx.getBean("baseMapper");
	}

	private void createDirectoryWhenNoExist(File file) {
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		}
	}

}
